//**
// sse,服务端主动向客户端发送消息
//  */

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/api/events', (req, res) => {
    // 设置响应头，指定为 SSE 类型
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('Access-Control-Allow-Origin',"*")
    res.flushHeaders();

    // 模拟每隔 3 秒向客户端发送一次数据
    const intervalId = setInterval(() => {
        const data = `data: ${new Date().toLocaleTimeString()}\n\n`;
        res.write(data);
    }, 3000);

    // 当客户端断开连接时，清除定时器
    req.on('close', () => {
        clearInterval(intervalId);
        res.end();
    });
});

const port = 3000;
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});